import {
  observable,
  extendObservable,
  computed,
  toJS,
  action
} from '../../libs/mobx';
import contestUtil from '../../utils/contestUtil.js';
import {
  reqHeader,
  proxy,
  banPNG
} from '../../utils/util.js';

import LoginStore from '../login/store.js';
import PhotoselectStore from '../photoselect/store.js';
const app = getApp();

var CurStore = function() {
  let me = this;
  let getDefault = function() {
    return {
      timeStr: '',
      contestCategoryId: '',
      contestCategoryType: '',
      contestCategoriesArray:[],
      cur_contest: {},
      photo:true,
      groupPhoto:false
    }
  }
  let getDefaultListOptions = function() {
    return {
      photoListUrl: '',
      params: {
        contestId: me.cur_contest && me.cur_contest.id ? me.cur_contest.id : '',
        page: 1,
        size: 20,
        type: 'json'
      }
    }
  }
  extendObservable(this, getDefault(), getDefaultListOptions());

  this.reset = action(() => {
    Object.assign(this, getDefault(), getDefaultListOptions());
  })

  this.setPhotoState = action((obj) => {
    this.photo = obj.photo;
    this.groupPhoto = obj.groupPhoto;
    this.graphic = obj.graphic;
  })

  this.setContestCategoryId = action((e) => {
    let paramObj = {};
    if (e.detail.type && e.detail.type === "prizeWorks") {
      paramObj={
        groupName: e.detail.name
      }
    }else{
      this.contestCategoryId = e.detail.id;
      this.contestCategoryType = e.detail.graphic ? 'graphic' : '';
      paramObj = {
        contestCategoryId: e.detail.id
      }
    }

    this.setPhotoListUrl(this.photoListUrl,paramObj);
  });


  this.setPhotoListUrl = action((str,paramObj) => {
    Object.assign(this, getDefaultListOptions(), {
      photoListUrl: str
    });
    Object.assign(this.params, paramObj);
    
  })

  this.nextPage = action(() => {
    this.params.page++;
  })
  this.getContestDetail = action((opts,callback) => {
    let contestID = opts.id || '315106abfc3e4a18a22e55e5be443532';
    //  'f3f835ebda8f4e57b76f5d7b76017749';
    wx.request({
      url: `${proxy}/contest/v4/data/detail`,
      data: {
        contestId: contestID,
        access_token: LoginStore.userInfo.access_token || ""
      },
      header: reqHeader,
      success: function(res) {
        if (res.statusCode != 200) {
          return;
        }
        res = res.data;
        if (res.status == 200) {

          let prizeMsg = res.data.contestPropertyInfo.prizeMsg;
          res.data.contestPropertyInfo.prizeMsg  = prizeMsg.replace(/&yen;/g, "¥");

          me.cur_contest = res.data;
          me.params.contestId = contestID;
          me.timeStr = contestUtil.getContestRTime(res.data);
          me.contestCategoriesArray = res.data.contestCategories;
          me.contestCategoryId = res.data.contestCategories[0].id;
          me.contestCategoryType = res.data.contestCategories[0].graphic ? 'graphic' : '';

          wx.setNavigationBarTitle({
            title: me.cur_contest.title
          }); 

          // if (!opts.contestCategories) {
          //   if (res.data.contestCategories && res.data.contestCategories.length) {
          //     me.contestCategoryId = res.data.contestCategories[0].id; 
          //   }
            
          // }

          if (callback){
            callback();
          }

        } else {
          console.log(res.message);
        }
      }
    });
  });

  this.cansai = action(function() {
    if (PhotoselectStore.activeNums) {
      var jsonArray = Object.keys(PhotoselectStore.activeJson);
      console.log(jsonArray)
      if (jsonArray.length) {

        wx.request({
          url: `${proxy}/contest/v3/data/joinWithExist`,
          data: {
            photoIds: jsonArray.join(','),
            contestCategoryId: app.globalData.selectedCategoryId,
            access_token: LoginStore.userInfo.access_token
          },
          header: reqHeader,
          success: function(res) {
            if (res.statusCode != 200) {
              return;
            }
            res = res.data;
            if (res.status == 200) {
              wx.showToast({
                mask: true,
                title: '参赛成功',
                icon: 'success',
                duration: 2000
              })
              setTimeout(function() {
                // wx.reLaunch({
                //   url: `/pages/contest/contest?id=${me.cur_contest.id}`
                // })
                let pages = getCurrentPages();
                let contestPage = pages[pages.length - 2];
                contestPage.setData({
                  freshMark: true
                }, function () {
                  wx.navigateBack({
                    delta: 1
                  })
                })
                
              }, 1000)
            } else {
              if (res.message === '您需要输入邀请码参赛！') {
                wx.showToast({
                  mask: false,
                  title: '大赛为邀请赛，请前往500px官网或App投稿',
                  icon: 'none',
                  duration: 2000
                })
              } else {
                wx.showToast({
                  mask: false,
                  title: res.message,
                  icon: 'none',
                  duration: 2000
                })
              }
            }
          }
        })
      } else {
        wx.showToast({
          mask: false,
          title: '没有可参赛作品',
          icon: 'none',
          duration: 2000
        })
      }
    }
  });

  this.takePhoto = action((callback,isAdd) => {
    let count = 9;
    if (this.photo && !this.groupPhoto) {
      count = 1;
    }

    wx.chooseImage({
      count: 9,
      sizeType: ['original'],
      sourceType: ['album'],
      success: function (res) {
        let path = res.tempFilePaths;
        if (!banPNG(path)){
          return;
        }
        if (!isAdd && !me.photo && me.groupPhoto && (path.length < 2)) {
          wx.showModal({
            title: '提示',
            content: '最少需要选择2张图片哦~',
            showCancel: false,
            confirmText: '好吧',
            confirmColor: '#0870D1'
          })
          return;
        }

        callback(path);
      }
    })
  })

}

export default new CurStore();